package org.september.pisces.user.permission.utils;

import java.util.Iterator;

import org.september.core.exception.BusinessException;
import org.september.pisces.user.permission.entity.SystemUser;
import org.september.simpleweb.model.WebConst;
import org.september.simpleweb.utils.SessionHelper;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import jakarta.servlet.http.HttpServletRequest;


public class UserSessionHelper {

	private static String WebTreeKeyPrefix="_menuTree_";
    public static Long getUserId() {
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert sra != null;
        HttpServletRequest req = sra.getRequest();
        String userIdString = req.getHeader("userId");
        if (!StringUtils.hasLength(userIdString)) {
            throw new BusinessException("请先登录");
        }
        return Long.parseLong(userIdString);
    }

	/**
	 * 获取当前登录后台用户对象
	 */
    public static SystemUser getLoginUser() {
    	//TODO 如果用户为空
        return SessionHelper.getSessionUser(SystemUser.class);
    }
	/**
	 * 当前登录后台用户对象
	 */
    public static void setLoginUser(SystemUser user) {
         SessionHelper.setSessionUser(user);
    }

    /**
     * 获取当前登录后台用户的id
     */
    public static Long getLoginUid() {
        return getLoginUser().getId();
    }

    public static String getLoginAccount() {
        return getLoginUser().getUsername();
    }
    
    public static void remove() {
        SessionHelper.getSession().removeAttribute(WebConst.Session.Session_User_Key);
        Iterator<String> it = SessionHelper.getSession().getAttributeNames().asIterator();
        while(it.hasNext()) {
        	String key = it.next();
        	if(key.startsWith(WebTreeKeyPrefix)) {
        		SessionHelper.getSession().removeAttribute(key);
        	}
        }
    }

    public static void setMenuTree(String groupName,Object modules) {
    	SessionHelper.getSession().setAttribute(WebTreeKeyPrefix+groupName, modules);
    }

    public static Object getMenuTree(String groupName){
    	return SessionHelper.getSession().getAttribute(WebTreeKeyPrefix+groupName);
    }

}
